package controller

import (
	"appService/src/application"
	"appService/src/application/app/appModels"
	"appService/src/application/request"
	"appService/src/authValid"
	"appService/src/authValid/userAuthType"
	"appService/src/config"
	"errors"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"xorm.io/builder"
	"xorm.io/xorm"
)

type Folder struct {
	application.BaseController
}
//getModel 获取控制器对应的 模型
func  (*Folder)getModel() appModels.IModel{
	return new(appModels.Folder)
}
//isRoles 判断用户是否有权限赋予角色给文件夹
func (this *Folder) isRoles(req *request.Request) {
	if config.FilesAuthOpen {
		folder :=req.Model.(*appModels.Folder)
		if req.LoginUser.Account.AccountType != userAuthType.SYSTEM_ADMIN {
			for _, v := range folder.Roles {
				for _,id:=range v.Roles{
					role := authValid.GetRole(id)
					if role == nil {
						req.JsonError("操作失败，角色不存在")
					} else {
						if role.RoleType > req.LoginUser.Account.AccountType {
							req.JsonErrorf("您没有权限赋予【%v】角色给该文件夹", role.RoleName)
						}
					}
				}
			}
		}
	}
}
//Add 添加
func (this *Folder) Add(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.AddEx(func(db *xorm.Session, guid string) error {
		return req.Model.Init(db, guid, req.LoginUser)
	}, func(db *xorm.Session) error {
		this.isRoles(req)
		return req.Model.AddValid()
	}, func(db *xorm.Session) error {
		folder := req.Model.(*appModels.Folder)
		if folder.Visit < userAuthType.GENERAL && folder.Visit > userAuthType.SYSTEM_ADMIN {
			folder.Visit = 1
		}
		if folder.Visit > req.LoginUser.Account.AccountType {
			folder.Visit = req.LoginUser.Account.AccountType
		}
		has, err := db.Where(builder.Eq{"folder_name":folder.FolderName}).Exist(new(appModels.Folder))
		if err != nil {
			g.Log().Errorf("查询【文件夹】名称是否存在，错误：%v", err)
			return errors.New("添加失败")
		}
		if has {
			return errors.New("文件夹名称已经存在")
		}
		return nil
	}, func() {
		folder := req.Model.(*appModels.Folder)
		authValid.FolderSet(folder)
	})
}

//Delete 删除
func (this *Folder) Delete(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	var ids []string
	req.DeleteEx(func(db *xorm.Session, id ...string) error {
		ids = id
		for _, id := range ids {
			_, err := authValid.FolderIdGetFolder(id, req.LoginUser)
			if err != nil {
				return err
			}
		}
		has, err := db.Where(builder.In("pid", ids)).Exist(new(appModels.Folder))
		if err != nil {
			g.Log().Errorf("查询【文件夹】是否可以删除，错误：%v", err)
			return errors.New("删除失败")
		}
		if has {
			return errors.New("删除的【文件夹】中，存在子文件夹")
		}
		has, err = db.Where(builder.In("folder_id", ids)).Exist(new(appModels.Files))
		if err != nil {
			g.Log().Errorf("查询【文件夹】是否可以删除，错误：%v", err)
			return errors.New("删除失败")
		}
		if has {
			return errors.New("删除的【文件夹】中，存在文件")
		}
		db.Where(builder.In("id", ids))
		return nil
	}, func() {
		for _, id := range ids {
			authValid.FolderRemove(id)
		}
	})
}

//Edit 修改
func (this *Folder) Edit(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.EditEx(func(db *xorm.Session) error {
		this.isRoles(req)
		return req.Model.EditValid()
	}, func(db *xorm.Session) error {
		folder := req.Model.(*appModels.Folder)
		if folder.Id == "" {
			return errors.New("请选择要修改的数据")
		}
		_, err := authValid.FolderIdGetFolder(folder.Id, req.LoginUser)
		if err != nil {
			return err
		}
		if folder.Visit < userAuthType.GENERAL && folder.Visit > userAuthType.SYSTEM_ADMIN {
			folder.Visit = 1
		}
		if folder.Visit > req.LoginUser.Account.AccountType {
			folder.Visit = req.LoginUser.Account.AccountType
		}
		temDb := db.Where(builder.Eq{"folder_name":folder.FolderName})
		temDb.Where(builder.Neq{"id": folder.Id})
		has, err :=temDb.Exist(new(appModels.Folder))
		if err != nil {
			g.Log().Errorf("查询【文件夹】名称是否存在，错误：%v", err)
			return errors.New("添加失败")
		}
		if has {
			return errors.New("文件夹名称已经存在")
		}
		db.Where(builder.Eq{"id": folder.Id})
		db.MustCols("pid")
		return nil
	}, func() {
		folder := req.Model.(*appModels.Folder)
		authValid.FolderSet(folder)
	})
}

//Get 获取一个文件夹的信息
func (this *Folder) Get(r *ghttp.Request) {
	p := struct {
		Id string `json:"id"`
	}{}
	req := this.NewRequest(r,this.getModel())
	req.ParamsAnalyse(&p)
	folder, err := authValid.FolderIdGetFolder(p.Id, req.LoginUser)
	if err != nil {
		req.JsonErrorf("%v", err)
	}
	req.JsonSuccessData(folder)
}

//List 获取可访问的文件夹列表
func (this *Folder) List(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.JsonSuccessData(authValid.GetALLUserFolder(req.LoginUser))
}
